package com.project.harmonyledger.service.impl.user.account;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.project.harmonyledger.common.response.Result;
import com.project.harmonyledger.common.response.ResultCode;
import com.project.harmonyledger.mapper.UserMapper;
import com.project.harmonyledger.pojo.User;
import com.project.harmonyledger.service.user.account.LoginService;
import com.project.harmonyledger.utils.JwtUtil;
import com.project.harmonyledger.utils.UserDetailsImpl;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

@Service
public class LoginServiceImpl implements LoginService {
  private static final Logger log = LoggerFactory.getLogger(LoginServiceImpl.class);
  @Autowired
  private AuthenticationManager authenticationManager;

  @Autowired
  private UserMapper userMapper;

  @Override
  public Result<Map<String, String>> getToken(String username, String password) {
    Map<String, String> map = new HashMap<>();
    try {
      ResultCode res = Judge(username, password);
      if (!res.getMessage().equals("success")) {
        map.put("message", res.getMessage());
        return Result.error(res, map);
      }

      // 封装用户名、密码
      UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(username,
          password);

      // 验证用户名和密码
      Authentication authenticate = authenticationManager.authenticate(authenticationToken);

      // 验证成功，生成token
      UserDetailsImpl loginUser = (UserDetailsImpl) authenticate.getPrincipal();
      User user = loginUser.getUser();
      String jwt = JwtUtil.createJWT(user.getId().toString());

      map.put("id", user.getId().toString());
      map.put("username", user.getUsername());
      map.put("nickname", user.getNickname());
      map.put("photo", user.getPhoto());
      map.put("token", jwt);
      return Result.success(map);

    } catch (BadCredentialsException e) {
      map.put("message", ResultCode.PASSWORD_ERROR.getMessage());
      return Result.error(ResultCode.PASSWORD_ERROR, map);
    } catch (Exception e) {
      log.error(e.getMessage());
      map.put("message", ResultCode.SYSTEM_ERROR.getMessage());
      return Result.error(ResultCode.SYSTEM_ERROR, map);
    }
  }

  public ResultCode Judge(String username, String password) {
    username = username.trim();
    if (username.isEmpty()) {
      return ResultCode.USERNAME_EMPTY;
    }
    if (password == null || password.isEmpty()) {
      return ResultCode.PASSWORD_EMPTY;
    }
    // 检查用户是否存在
    QueryWrapper<User> queryWrapper = new QueryWrapper<>();
    queryWrapper.eq("username", username);
    User user = userMapper.selectOne(queryWrapper);
    if (user == null) {
      return ResultCode.USER_NOT_FOUND;
    }
    return ResultCode.SUCCESS;
  }
}
